import { checkAllCart, insertCart, findCartList, deleteCart, updateCart } from '@/api/cart'

export default {
  namespaced: true,
  state: {
    cartList: []
  },
  getters: {
    // 商品总数：cartList中每一项的count字段的值累加起来
    allCount (state) {
      return state.cartList.reduce((p, c) => p + c.count, 0)
    },
    // 价钱总数: cartList中每一项的单价price * 数量count累加起来
    priceCount (state) {
      return state.cartList.reduce((p, c) => p + c.count * c.price, 0)
    },
    // 已选择的总数: 把cartList中所有项中selected为true的项的count做累加 filter + reduce
    selectedCount (state) {
      return state.cartList
        .filter(item => item.selected)
        .reduce((p, c) => p + c.count, 0)
    },
    // 已选择的商品钱数总和:把cartList中所有项中selected为true的项的筛选出来 让后把他们的count * price累加
    selectedPrice (state) {
      return state.cartList
        .filter(item => item.selected)
        .reduce((p, c) => p + c.count * c.price, 0)
    },
    isAll (state) {
      return state.cartList.every(item => item.selected)
    }
  },
  mutations: {
    // 单选修改
    singleCheck (state, { skuId, selected }) {
      // 1. 根据skuId找到要修改的那一项 find findIndex
      const item = state.cartList.find(item => item.skuId === skuId)
      // 2. 找到之后把它里面的selected字段修改为传入的selected
      item.selected = selected
    },
    setCartList (state, list) {
      state.cartList = list
    }
  },
  actions: {
    // 加入购物车
    async fetchInsertCart (ctx, { skuId, count }) {
      // 1. 加入购物车接口
      await insertCart({ skuId, count })
      // 2. 获取购物车列表
      const res = await findCartList()
      // 3. 调用mutation存入state
      ctx.commit('setCartList', res.data.result)
    },
    // 删除购物车
    async fetchDelCart (ctx, ids) {
      // 1. 调用删除购物车接口
      await deleteCart(ids)
      // 2. 获取购物车列表
      const res = await findCartList()
      // 3. 调用mutation存入state
      ctx.commit('setCartList', res.data.result)
    },
    // 单选购物车实现
    async fetchCheckCart (ctx, goods) {
      // 1.调用单选接口
      await updateCart(goods)
      // 2. 获取购物车列表
      const res = await findCartList()
      // 3. 调用mutation存入state
      ctx.commit('setCartList', res.data.result)
    },
    // 数量修改
    async fetchCount (ctx, goods) {
      // 1.调用数量修改接口
      await updateCart(goods)
      // 2. 获取购物车列表
      const res = await findCartList()
      // 3. 调用mutation存入state
      ctx.commit('setCartList', res.data.result)
    },
    // 全选
    async fetchAllCheck (ctx, selected) {
      await checkAllCart({
        selected,
        ids: ctx.state.cartList.map(item => item.skuId)
      })
      // 2. 获取购物车列表
      const res = await findCartList()
      // 3. 调用mutation存入state
      ctx.commit('setCartList', res.data.result)
    }
  }
}
